package org.example.stringbootmybatisplus.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.example.stringbootmybatisplus.entity.Bookstore;
import org.example.stringbootmybatisplus.service.BookstoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
//@RequestMapping("/books")
public class BookstoreController {
    @Autowired
    BookstoreService bookstoreService;

    @GetMapping
    public String books(Model model) {
        List<Bookstore> list = bookstoreService.list();
        model.addAttribute("list", list);
        return "books";
    }

    @PostMapping
    public String searchBook(Model model, Bookstore bookstore) {
        List<Bookstore> list = bookstoreService.searchBook(bookstore);
        model.addAttribute("list", list);
        model.addAttribute("name", bookstore.getName());
        model.addAttribute("category", bookstore.getCategory());
        model.addAttribute("author", bookstore.getAuthor());
        return "books";
    }

    //分页/查询
    @GetMapping("/page")
    public String page(Model model, @RequestParam(defaultValue = "1") Integer pageNum, Bookstore bookstore) {
        IPage page = bookstoreService.getPage(pageNum, bookstore);
        model.addAttribute("page", page);
        model.addAttribute("name", bookstore.getName());
        model.addAttribute("category", bookstore.getCategory());
        model.addAttribute("author", bookstore.getAuthor());
        return "bookPage";
    }

    //    跳转到新增页面
    @RequestMapping("/toAdd")
    public String toAdd() {
        return "insertBook";
    }

    //    新增
    @PostMapping("/addBook")
    public String addAllBook(Bookstore bookstore) {
        bookstoreService.addAllBook(bookstore);
        return "redirect:/page";
    }

    //    跳转到修改
    @RequestMapping("/updBook/{id}")
    public String updBook() {
        return "updateBook";
    }

    //    修改
    @PostMapping("/updateBook")
    public String updBook(Bookstore bookstores, Model model) {
        boolean bookstore = bookstoreService.updateBook(bookstores);
        model.addAttribute("bookstore", bookstore);
        return "redirect:/page";
    }

}
